package cn.com.surker.wechat;

import cn.com.surker.common.HttpRequestHelper;
import cn.com.surker.redis.RedisUtils;
import cn.com.surker.spring.SpringContextHolder;
import cn.com.surker.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @Author lucky
 * @create 2021年03月24 14:53
 * @desc
 */
public class WechatSignGroupApi {

    private static Logger log = LoggerFactory.getLogger(WechatSignGroupApi.class);

    /**企业微信的**/
    public static String corpID = "wwd85ae41a2d988bc8";
    /**打卡密匙**/
    public static String signSecret = "207WXjnf3LhMbQ8o31s77wtzfV8jyKevDyAktAzQZ40";
    /**打卡应用**/
    public static String agentId = "3010011";
    /**缓存键**/
    public static String accessTokenKey = "oa_cloud_sign_access_token_key";

    public static String ticketKey = "group_surker_cloud_js_ticket";
    /**缓存时间**/
    public static Long sessionExpired = 7200L;

    public static void main(String[] args){

//        getUser("wwd85ae41a2d988bc8", "v8VgA-JM7T7s8G5JfTqYFDbYcR3H_om09jkcBHAttUc", "lucky");

//        String touser = "lucky|1mj1482|1lgq996|1lt1556";
//        String msgType = "textcard";
//        String title = "驰旭集团生产早汇报";
//        String description = "驰旭集团生产2021年12月15日";
//        String url2 = "http://surker.chixugroup.com/cloud/index";
//        Boolean boo = sendTextCardMessage(touser, msgType, title, description, url2);
//        String token = "U7J2QXB8Cann3djaLUFBfqPVUaghE1cmRI1GGVglQLqGWh79V_A1h-Fydt8mCZJYMIgBJv1mHq5tEF6-SXyI25QF7Fz3KitI_4QfuvJG9OmrE6ryme5rXQaJcCd5EE-0x81uyCG8p8aOC2jsm7qFfJA_cIXrlb_3K1q5KAi7i_lsq_EzxlX_1pk_443sgb3dW9XAYIzYcBdAfnS9xLmDMA";
//
//        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpID + "&corpsecret=" + corpOriginSecret;
//
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpID + "&corpsecret=" + signSecret;

//        String token = loadGroupOriginToken(corpID, corpOriginSecret);
        String token = "LrKGdqi_hQUobCR7c43voPJAxJAkCbjYW1dj0KVJA0fzXH3ehEXcTtyUsWUU62Krgb7HtYe0WS5SiYI3hF-tajJg7TzvyYyhSADGJVY20iK16QfbjaBCXOvxG0pWkbMpgFN5mxu9WxtoEItUN1eN9MGkOnovnNwMv3g5D2oqiafRWpfqxAPrSsYhIRdWAksarQMCNSKiLYihhZlDHWFqHw";
//        sendTextCardMessage (token, "lucky|1lt1556", "textcard", "测试111", "textcardtextcardtextcard",
//                "http://surker.chixugroup.com/cloud/order/records?title=122332fererwe");
//        JSONObject json = new JSONObject();
//        json.put("id", 318);
//        JSONObject j = deleteUserOrDepartment(corpID, corpOriginSecret,
//                "https://qyapi.weixin.qq.com/cgi-bin/department/delete", json);
//        System.out.println(j);
//        sendButtonMessage(corpID, corpSecret, agentId, "lucky", "button_interaction", "测试项目",
//                "材料付款--流程编号:CXM00011,申请人:万强,付款合同:测试大,总金额:4343.0元", null, "http://surker.chixugroup.com");
//        updateCardMessage(null, null, null, null, null, "");
//        sendCardMessage(null, null, null, null, null, null, null, null);
//        url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + token + "&id=2";
//        try {
//            String res = HttpRequestHelper.get(url);
//            JSONObject obj = JSONObject.parseObject(res);
//            System.out.println(obj);
//            log.info("企业微信获取access_token:{},token_url:{}", res, url);
//            if("ok".equals(obj.getString("errmsg"))){
//                log.info("验证后的access_token:{}", obj.getString("access_token"));
//            } else {
//                log.error("获取企业微信API token失败：" + res);
//            }
//        } catch (Exception e) {
//            log.error("获取企业微信API token失败：" + e.getMessage(), e);
//        }
//        JSONObject jo = getReportOrderDetail("", "", "86hgBrRuaewHMeURgpg3ajaMmGXMDftkCeybbxzY4bhn25h7unVcdMKGQzpHRX6XsL");
//        System.out.println(11);
//        System.out.println(jo.toString());
//        System.out.println(DateUtil.convertLong("2023-03-10 00:00:00") + "   " + new Date().getTime());
//        getReportOrderNo("", "", DateUtil.convertLong("2023-03-10 00:00:00") / 1000,
//                new Date().getTime() / 1000, 0, 50, "3WLJ7PEgtXMdpihCQCJa7YaSK81Goz9Jk8RfnewR");
//        sendTextMessage("","","lucky")
        JSONObject jo = new JSONObject();
        JSONObject arJ = new JSONObject();

        JSONArray ja = new JSONArray();
        JSONObject json1 = new JSONObject();
        json1.put("title", "罗涛(2023年3月22日 21时27分) 外勤打卡");
        json1.put("description", "重庆市江津区双福街道福星大道172号祥瑞·西城中心");
        json1.put("url", "https://surker.chixugroup.com/cloud/index");
        json1.put("picurl", "https://cloud.chixugroup.com/file/preview/16022");
        ja.add(json1);
        arJ.put("articles", ja);
        System.out.println(jo.toString());
        sendTextImageMessage("", "", "lucky|1lt1556|1tt1632", "", "news", arJ);
//        sendTextMessage("", "", "", "lucky", "测试三大厦");
    }

    /**
     * 获取企业微信应用的JS_Ticket
     * @return
     */
    public static String getAgentJsTicket(String corpid, String secret) {
        if (StringUtils.isNull(corpid))
            corpid = corpID;
        if (StringUtils.isNull(secret))
            secret = signSecret;
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        String key = corpid + "_" + ticketKey;
        /**判断ticket签名是否存在**/
        if (redisUtils.exists(key)) {
            return StringUtils.convertString(redisUtils.get(key));
        }
        String accessToken = loadGroupToken(corpid, secret);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=" + accessToken + "&type=agent_config";
        try {
            String res = HttpRequestHelper.get(url);
            JSONObject obj = JSONObject.parseObject(res);
            if(obj.getInteger("errcode") == 0 && !StringUtils.isNull(obj.getString("ticket"))){
                log.info("ticket=" + obj.getString("ticket"));
                redisUtils.set(key, obj.getString("ticket"), sessionExpired);
                return obj.getString("ticket");
            } else if (obj != null && obj.getInteger("errcode") == 40001) {
                redisUtils.remove(accessTokenKey);
                return getAgentJsTicket(corpid, secret);
            } else {
                log.error("获取企业微信应用API JS_Ticket失败：" + res);
                return "";
            }
        } catch (Exception e) {
            log.error("获取企业微信应用API JS_Ticket失败：" + e.getMessage(), e);
            return "";
        }
    }

    /**
     * 企业微信加密签名
     * @param nonceStr
     * @param url
     * @param ticket
     * @param timestamp
     * @return
     */
    public static String jsApiSignature(String nonceStr, String url, String ticket, Long timestamp){
        String str = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url="+url;
        log.error("jsApiSign sinStr:" + str);
        String signature = WechatAccountApi.sha1(str).toLowerCase();
        log.error("jsApiSign signature:" + signature);
        return signature;
    }

    /**
     * 获取企业微信的JS_Ticket
     * @return
     */
    public static String getJsTicket(String corpid, String secret) {
        if (StringUtils.isNull(corpid))
            corpid = corpID;
        if (StringUtils.isNull(secret))
            secret = signSecret;
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        String key = corpid + "_" + ticketKey;
        /**判断ticket签名是否存在**/
        if (redisUtils.exists(key)) {
            return StringUtils.convertString(redisUtils.get(key));
        }
        String tokenKey = corpid + "_" + accessTokenKey;
        String accessToken = "";
        if(redisUtils.exists(tokenKey))
            accessToken = StringUtils.convertString(redisUtils.get(tokenKey));
        else
            accessToken = loadGroupToken(corpid, secret);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + accessToken;
        try {
            String res = HttpRequestHelper.get(url);
            JSONObject obj = JSONObject.parseObject(res);
            if(obj.getInteger("errcode") == 0 && !StringUtils.isNull(obj.getString("ticket"))){
                log.info("ticket=" + obj.getString("ticket"));
                redisUtils.set(key, obj.getString("ticket"), sessionExpired);
                return obj.getString("ticket");
            } else if (obj != null && obj.getInteger("errcode") == 40001) {
                redisUtils.remove(tokenKey);
                loadGroupToken(corpid, secret);
                return getJsTicket(corpid, secret);
            } else {
                log.error("获取企业微信API JS_Ticket失败：" + res);
                return "";
            }
        } catch (Exception e) {
            log.error("获取企业微信API JS_Ticket失败：" + e.getMessage(), e);
            return "";
        }
    }

    /**
     * 企业微信推送信息
     * @param touser 接收用户
     * @param msgType 消息类型news
     * @return
     */
    public static Boolean sendTextImageMessage(String token,String touser, String agentid, String msgType, JSONObject newsJson) {
        /**请求参数**/
        JSONObject json = new JSONObject();

        if (StringUtils.isNull(agentid))
            agentid = agentId;
        json.put("touser", touser);
        json.put("msgtype", msgType);
        json.put("agentid", agentid);
        json.put("news", newsJson);
        try {
            /**消息请求地址**/
            String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;
            /**请求结果**/
            String result = HttpRequestHelper.senPostJson(postUrl, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(result);
            Integer code = obj.getInteger("errcode");
            if(code == 0){
                return true;
            } else {
                log.error("企业微信推送信息失败：" + result);
                return false;
            }
        } catch (Exception e) {
            log.error("获取企业微信用户信息失败：" + e.getMessage(), e);
            return false;
        }
    }

    /**
     * 企业微信推送信息
     * @param corpid 企业微信应用ID
     * @param secret 应用secret
     * @param touser 接收用户
     * @param msgType 消息类型news
     * @return
     */
    public static Boolean sendTextImageMessage(String corpid, String secret,String touser, String agentid,
                                               String msgType, JSONObject newsJson) {
        if (StringUtils.isNull(corpid))
            corpid = corpID;
        if (StringUtils.isNull(secret))
            secret = signSecret;
        if (StringUtils.isNull(agentid))
            agentid = agentId;
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        String tokenKey = corpid + "_" + accessTokenKey;
        String accessToken = "";
//        String accessToken = "SaXHhrYAmL8gPQZZ6tu0a_9ANYk3WUKqXeGl4nOr5QdB8Caq491nmF6ut5gGoQrYdUxwt12h7s1mptmPfkSqppBXnvOFHf8mqU4tGEC7FgSfaDgqUw9ITnLWPXFXEO2DnTv4N3uBlrhyqlfFHeIFLzqGKVkk_wdkRT8fYpQD2YcwVelx-TD_pyeZD5hS70WVyg0heuRbmg6YohL3jIDMdg";

        if(redisUtils.exists(tokenKey))
            accessToken = StringUtils.convertString(redisUtils.get(tokenKey));
        else
            accessToken = loadGroupToken(corpid, secret);
        /**请求参数**/
        JSONObject json = new JSONObject();

        json.put("touser", touser);
        json.put("msgtype", msgType);
        json.put("agentid", agentid);
        json.put("news", newsJson);
        try {
            /**消息请求地址**/
            String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
            /**请求结果**/
            String result = HttpRequestHelper.senPostJson(postUrl, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(result);
            Integer code = obj.getInteger("errcode");
            if(code == 0){
                return true;
            } else if (code == 42001 || code == 40014 || code == 41001){//token失效
                log.error("企业微信用户验证token失效，重新获取token");
                redisUtils.remove(tokenKey);
                loadGroupToken(corpid, secret);
                return sendTextImageMessage(corpid, secret, touser, msgType, newsJson);
            } else {
                log.error("企业微信推送信息失败：" + result);
                return false;
            }
        } catch (Exception e) {
            log.error("获取企业微信用户信息失败：" + e.getMessage(), e);
            return false;
        }
    }

    /**
     * 企业微信推送信息
     * @param corpid 企业微信应用ID
     * @param secret 应用secret
     * @param touser 接收用户
     * @param content 描述
     * @return
     */
    public static Boolean sendTextMessage(String corpid, String secret, String agentid, String touser, String content) {
        if (StringUtils.isNull(corpid))
            corpid = corpID;
        if (StringUtils.isNull(secret))
            secret = signSecret;
        if (StringUtils.isNull(agentid))
            agentid = agentId;
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        String tokenKey = corpid + "_" + accessTokenKey;
                String accessToken = "";
//        String accessToken = "SaXHhrYAmL8gPQZZ6tu0a_9ANYk3WUKqXeGl4nOr5QdB8Caq491nmF6ut5gGoQrYdUxwt12h7s1mptmPfkSqppBXnvOFHf8mqU4tGEC7FgSfaDgqUw9ITnLWPXFXEO2DnTv4N3uBlrhyqlfFHeIFLzqGKVkk_wdkRT8fYpQD2YcwVelx-TD_pyeZD5hS70WVyg0heuRbmg6YohL3jIDMdg";

        if(redisUtils.exists(tokenKey))
            accessToken = StringUtils.convertString(redisUtils.get(tokenKey));
        else
            accessToken = loadGroupToken(corpid, secret);
        /**请求参数**/
        JSONObject textJson = new JSONObject();
        JSONObject json = new JSONObject();
        textJson.put("content", content);

        json.put("touser", touser);
        json.put("agentid", agentid);
        json.put("msgtype", "text");
        json.put("text", textJson);
        try {
            /**消息请求地址**/
            String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
            /**请求结果**/
            String result = HttpRequestHelper.senPostJson(postUrl, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(result);
            Integer code = obj.getInteger("errcode");
            if(code == 0){
                return true;
            } else if (code == 42001 || code == 40014 || code == 41001){//token失效
                log.error("企业微信用户验证token失效，重新获取token");
//                redisUtils.remove(tokenKey);
//                loadGroupToken(corpid, secret);
                return sendTextMessage(corpid, secret, agentid, touser, content);
            } else {
                log.error("企业微信推送信息失败：" + result);
                return false;
            }
        } catch (Exception e) {
            log.error("获取企业微信用户信息失败：" + e.getMessage(), e);
            return false;
        }
    }

    /**
     * 企业微信推送信息
     * @param touser 接收用户
     * @param msgType 消息类型
     * @param title 标题
     * @param description 描述
     * @param url 跳转地址
     * @return
     */
    public static Boolean sendTextCardMessage(String token, String touser, String msgType,
                                              String title, String description, String url) {
        /**请求参数**/
        JSONObject textJson = new JSONObject();
        JSONObject json = new JSONObject();
        textJson.put("title", title);
        textJson.put("description", description);
        textJson.put("url", url);

        json.put("touser", touser);
        json.put("msgtype", msgType);
        json.put("agentid", agentId);
        json.put("textcard", textJson);
        try {
            /**消息请求地址**/
            String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;
            /**请求结果**/
            String result = HttpRequestHelper.senPostJson(postUrl, json.toJSONString());
            System.out.println(result);

            JSONObject obj = JSONObject.parseObject(result);
            Integer code = obj.getInteger("errcode");
            if(code == 0){
                return true;
            } else {
                log.error("企业微信推送信息失败：" + result);
                return false;
            }
        } catch (Exception e) {
            log.error("获取企业微信用户信息失败：" + e.getMessage(), e);
            return false;
        }
    }

    /**
     *  加载企业微信的token
     * @param corpid 企业微信应用ID
     * @param secret 应用secret
     */
    public static String loadGroupToken(String corpid, String secret) {
        if (StringUtils.isNull(corpid))
            corpid = corpID;
        if (StringUtils.isNull(secret))
            secret = signSecret;
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        /**缓存key**/
        String tokenKey = corpid + "_" + accessTokenKey;
        if (redisUtils.exists(tokenKey))
            return StringUtils.convertString(redisUtils.get(tokenKey));

        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + signSecret;

        try {
            String res = HttpRequestHelper.get(url);
            JSONObject obj = JSONObject.parseObject(res);
            log.error("企业微信获取access_token:{},token_url:{}", res, url);
            if("ok".equals(obj.getString("errmsg"))){
                log.info("验证后的access_token:{}", obj.getString("access_token"));
                redisUtils.set(tokenKey, obj.getString("access_token"), sessionExpired);
                return obj.getString("access_token");
            } else {
                log.error("获取企业微信API token失败：" + res);
                return "";
            }
        } catch (Exception e) {
            log.error("获取企业微信API token失败：" + e.getMessage(), e);
            return "";
        }
    }

}
